package com.example.demo.controller;

import com.example.demo.utils.RedisLockUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class UserController {
    private String goodNumKey = "num";
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RedisLockUtils redisLock;

    /**
     * 设置商品库存
     * @param num 库存数量
     * @return
     */
    @GetMapping("/set-num/{num}")
    public int setNum(@PathVariable int num) {

        redisTemplate.opsForValue().set(goodNumKey, num);
        return num;
    }

    /**
     * 获取商品库存
     * @return
     */
    @GetMapping("/get-num")
    public int getNum() {
        Object objNum = redisTemplate.opsForValue().get(goodNumKey);
        int num = Integer.parseInt((String) objNum);
        return num;
    }

    /**
     * 用户带着id来秒杀商品
     * @param id 用户id
     * @return
     */
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable String id) {

        String key = "user:" + id;

        String productId = "product001";
        String requestId = productId + Thread.currentThread().getId();
        boolean locked = redisLock.lock(productId, requestId, 10);

        //如果存在直接返回结果
        if (redisTemplate.hasKey(key)) {
            return (String) redisTemplate.opsForValue().get(key);
        }
        //如果有锁重试
        if (!locked) {
            return "error";
        }
        try {
            //查询库存
            Object objNum = redisTemplate.opsForValue().get(goodNumKey);
            int num = Integer.parseInt((String) objNum);
            if (num > 0) {
                num--;
                //保存库存
                redisTemplate.opsForValue().set(goodNumKey, num);
                //添加抢购成功的信息
                redisTemplate.opsForValue().set(key, 1);
                System.out.println(key + "成功");
                return (String) redisTemplate.opsForValue().get(key);
            } else {
                //添加抢购失败的信息
                System.out.println(key + "失败");
               // redisTemplate.opsForValue().set(key, 0);
                return "0";
            }

        } finally {
            redisLock.unlock2(productId, requestId);
        }
    }

    // 其他接口方法...
}
